﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Design;
using System.Drawing.Imaging;
using System.Drawing.Text;
using System.Web;
using System.Net;


namespace Common
{
    public class PhotoHelper
    {
        
        #region 上传原图片
        /// <summary>
        /// 上传原始图片，自动生成文件名，成功则返回图片名称 
        /// </summary>
        public static string Upload(HttpPostedFile pos, string absPath)
        {
            string fileName = CreateFileName(pos, "t17");
            return Upload(pos, absPath, fileName);
        }

        /// <summary>
        /// 上传原始图片，手工指定文件名
        /// </summary>
        public static string Upload(HttpPostedFile pos, string absPath, string fileName)
        {
            try
            {
                if (pos == null) throw new Exception("HttpPostedFile出错: 上传图片不能为null");

                //验证绝对路径
                absPath = ValidAbsPath(absPath);
                //设置保存路径                
                string savePath = absPath + fileName;
                //保存图片
                pos.SaveAs(savePath);   
                             
                return fileName;
            }
            catch (System.Exception ex)
            {
                throw new Exception("上传原始图片出错：" + ex.Message);
            }
        }
        #endregion
        
        #region 上传缩略图
        /// <summary>
        /// 上传缩略图，自动生成文件名，成功后返回图片名
        /// </summary>        
        public static string ThumbStream(HttpPostedFile pos, int thumbW, int thumbH, string absPath)
        {
            string fileName = CreateFileName(pos, "t17");
            return ThumbStream(pos, thumbW, thumbH, absPath, fileName);
        }
        /// <summary>
        /// 上传缩略图，手工指定文件名
        /// </summary>
        public static string ThumbStream(HttpPostedFile pos, int thumbW, int thumbH, string absPath, string fileName)
        {
            try
            {
                if (pos == null) throw new Exception("上传图片出错: 缩略图不能为 null !"); 

                //验证绝对路径
                absPath = ValidAbsPath(absPath);

                //设置保存路径                
                string savePath = absPath + fileName;
                
                using (System.Drawing.Image img = Image.FromStream(pos.InputStream))
                {
                    System.Drawing.Size size = GetThumbSize(thumbW, thumbH, img.Width, img.Height);
                    int w = size.Width;
                    int h = size.Height;

                    using (Bitmap bmp = new Bitmap(w, h, PixelFormat.Format64bppArgb))
                    {
                        using (Graphics g = Graphics.FromImage(bmp))
                        {
                            //绘制缩略图
                            g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                            g.PixelOffsetMode = PixelOffsetMode.HighQuality;
                            g.Clear(Color.White);
                            g.DrawImage(img, 0, 0, w, h);

                            //保存
                            ImageFormat imgType = CreateFileType(pos);
                            bmp.Save(savePath, imgType);

                            //释放内存 
                            g.Dispose();
                            bmp.Dispose();
                            img.Dispose();
                        }
                    }
                }
                return fileName;
            }
            catch (System.Exception ex)
            {
                throw (ex);
            }
        }

        /// <summary>
        /// 根据原始图片名称生成缩略图，成功后返回图片名
        /// </summary> 
        public static string ThumbFiles(string sourceFileName, int thumbW, int thumbH, string absPath)
        {
            string fileName = CreateFileName(sourceFileName, "t17"); 
            return ThumbFiles(sourceFileName, thumbW, thumbH, absPath, fileName);
        }
        public static string ThumbFiles(string sourceFileName, int thumbW, int thumbH, string absPath, string fileName)
        {
            try
            {
                //验证绝对路径
                absPath = ValidAbsPath(absPath);

                //设置保存路径                
                string savePath = absPath + fileName; 
                
                using (System.Drawing.Image img = Image.FromFile(sourceFileName))
                {
                    System.Drawing.Size size = GetThumbSize(thumbW, thumbH, img.Width, img.Height);
                    int w = size.Width;
                    int h = size.Height;

                    using (Bitmap bmp = new Bitmap(w, h, PixelFormat.Format64bppArgb))
                    {
                        using (Graphics g = Graphics.FromImage(bmp))
                        {
                            //绘制缩略图
                            g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                            g.PixelOffsetMode = PixelOffsetMode.HighQuality;
                            g.Clear(Color.White);
                            g.DrawImage(img, 0, 0, w, h);

                            //保存
                            ImageFormat imgType = CreateFileType(sourceFileName);
                            bmp.Save(savePath, imgType);

                            //释放内存 
                            g.Dispose();
                            bmp.Dispose();
                            img.Dispose();
                        }
                    }
                }
                return fileName;
            }
            catch (System.Exception ex)
            {
                throw (ex);
            }
        }        
        #endregion
        
        #region 上传原图或缩略图
        /// <summary>
        /// 上传原图或压缩 (根据图片最大宽高决定)，指定文件名
        /// </summary>       
        public static string UploadOrThumb(HttpPostedFile pos, int maxWidth, int maxHeight, string absPath)
        {
            string fileName = CreateFileName(pos, "t17");
            return UploadOrThumb(pos, maxWidth, maxHeight, absPath, fileName);
        }
        public static string UploadOrThumb(HttpPostedFile pos, int maxWidth, int maxHeight, string absPath, string fileName)
        {
            try
            {
                if (pos == null) throw new Exception("上传图片出错: 缩略图不能为 null !"); 

                int w,h;
                                
                //判断文件的大小
                using (Image img = Image.FromStream(pos.InputStream))
                {
                    w = img.Width;
                    h = img.Height;
                    img.Dispose();
                }
                                
                //如果原图宽度大于高度，以宽度为准，超出则压缩
                if (w > h)
                {
                    if (w > maxWidth)return ThumbStream(pos, maxWidth, maxHeight, absPath, fileName);                    
                    else return Upload(pos, absPath, fileName);                    
                }
                else
                {
                    if (h > maxHeight) return ThumbStream(pos, maxWidth, maxHeight, absPath, fileName);
                    else return Upload(pos, absPath, fileName);                    
                }
            }
            catch (System.Exception ex)
            {
                throw new Exception("上传图片或压缩错误：" + ex.Message);                
            }

        }
                
        #endregion
                                
        #region 裁切图片
        /// <summary>
        /// 裁切并保存，成功后返回图片名
        /// </summary>
        public static string Crop(string fileName, string absPath, int w, int h, int x, int y)
        {
            try
            {
                //验证绝对路径
                absPath = ValidAbsPath(absPath);

                //设置保存路径
                string newFileName = "c_" + DateHelper.T14 + System.IO.Path.GetExtension(fileName);
                string sourcePath = absPath + fileName;
                string savePath = absPath + newFileName;

                //裁切
                using (Image imgSource = Image.FromFile(sourcePath))
                {
                    using (Bitmap bmp = new Bitmap(w, h, imgSource.PixelFormat))
                    {
                        bmp.SetResolution(imgSource.HorizontalResolution, imgSource.VerticalResolution);
                        using (Graphics g = Graphics.FromImage(bmp))
                        {
                            g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                            g.PixelOffsetMode = PixelOffsetMode.HighQuality;
                            g.Clear(Color.White);
                            g.DrawImage(imgSource, new Rectangle(0, 0, w, h), x, y, w, h, GraphicsUnit.Pixel);

                            //保存缩略图
                            ImageFormat imgType = CreateFileType(fileName);
                            bmp.Save(savePath, imgType);

                            g.Dispose();
                            bmp.Dispose();
                            imgSource.Dispose();
                        }
                    }
                }

                //删除临时原图
                if (System.IO.File.Exists(sourcePath)) System.IO.File.Delete(sourcePath);

                return newFileName;
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }
        #endregion
        
        #region ** 删除图片 **
        /// <summary>
        /// 删除图片
        /// </summary>
        public static void DeleteImage(string absPathFile)
        {
            try
            {
                //是否绝对路径
                if (absPathFile.Substring(1, 1) != @":") absPathFile = System.Web.HttpContext.Current.Server.MapPath(absPathFile);
                
                //是否存在文件
                if (System.IO.File.Exists(absPathFile)) System.IO.File.Delete(absPathFile);
            }
            catch (System.Exception ex)
            {
                throw (ex);
            }
        }
        #endregion
        
        #region ** 下载图片 **
        /// <summary>
        /// 通过URL下载图片，并保存到目录
        /// </summary> 
        public static void Download(string fUrl, string absPath)
        {
            try
            {
                string newFileName = fUrl.Substring(fUrl.LastIndexOf("/") + 1);
                absPath = ValidAbsPath(absPath);
                string savePath = absPath + newFileName; 

                using (WebClient client = new WebClient())
                {
                    client.DownloadFile(fUrl, savePath);
                    client.Dispose();
                }
            }
            catch (Exception ex)
            {
                throw ex; 
            }
        }

        /// <summary>
        /// 批量下载文本文件中的下载文件列表，一行一行的下载
        /// </summary>
        public static void DownloadList(string txtPath, string absPath)
        {
            if (!System.IO.File.Exists(txtPath)) throw new Exception("没有文本文件");
            
            List<string> list = new List<string>();
            absPath = ValidAbsPath(absPath);

            try
            {
                using (WebClient client = new WebClient())
                {
                    using (StreamReader reader = new StreamReader(txtPath))
                    {
                        string s = "";
                        while (s != null)
                        {
                            s = reader.ReadLine();
                            if (s != null)
                            {
                                string newFileName = s.Substring(s.LastIndexOf("/") + 1);
                                string savePath = absPath + newFileName;
                                client.DownloadFile(s, savePath);
                            }
                        }
                        reader.Close();
                    }
                }
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
        }
        #endregion
        
        #region ** 公共方法 ** 
        /// <summary>
        /// 验证绝对路径
        /// </summary>
        public static string ValidAbsPath(string absPath)
        {
            if (absPath.Substring(1, 1) != @":") absPath = System.Web.HttpContext.Current.Server.MapPath(absPath);
            if (!absPath.EndsWith("\\")) absPath += "\\";
            if (!System.IO.Directory.Exists(absPath)) System.IO.Directory.CreateDirectory(absPath);
            return absPath;
        }             

        /// <summary>
        /// 生成文件名
        /// </summary>
        public static string CreateFileName(HttpPostedFile pos)
        {
            return CreateFileName(pos.FileName,"t17");
        }        
        public static string CreateFileName(HttpPostedFile pos, string t)
        {
            return CreateFileName(pos.FileName, t);
        }
        public static string CreateFileName(string fileName)
        {
            return CreateFileName(fileName, "t17");
        }
        public static string CreateFileName(string fileName, string t)
        {
            string ext = System.IO.Path.GetExtension(fileName); 
            string s = String.Empty;
            switch (t)
            {
                case "t8": s = DateHelper.T8 + ext; break;
                case "t14": s = DateHelper.T14 + ext; break;
                case "t17": s = DateHelper.T17 + ext; break;
            }
            return s;
        }   
        
        /// <summary>
        /// 生成文件类型
        /// </summary>
        public static System.Drawing.Imaging.ImageFormat CreateFileType(string fName)
        {
            string ext = System.IO.Path.GetExtension(fName);
            System.Drawing.Imaging.ImageFormat imgType;

            switch (ext.ToLower())
            {
                case "jpeg" :
                case "jpg"  : imgType = ImageFormat.Jpeg; break;
                case "gif"  : imgType = ImageFormat.Gif;  break;
                case "png"  : imgType = ImageFormat.Png;  break;
                case "bmp"  : imgType = ImageFormat.Bmp;  break;
                default     : imgType = ImageFormat.Jpeg; break;
            }
            return imgType;
        }
        public static System.Drawing.Imaging.ImageFormat CreateFileType(HttpPostedFile pos)
        {
            return CreateFileType(pos.FileName);
        }

        /// <summary>
        /// 获取缩略图尺寸 (最大宽，最大高，实际宽，实际高) 返回按比例缩略后的宽高
        /// </summary>
        public static System.Drawing.Size GetThumbSize(int maxWidth, int maxHeight, int imgWidth, int imgHeight)
        {
            int w, h;

            if (imgWidth > imgHeight)
            {
                w = maxWidth;
                h = (int)((double)imgHeight / (double)imgWidth * (double)maxWidth);
            }
            else
            {
                h = maxHeight;
                w = (int)((double)imgWidth / (double)imgHeight * (double)maxHeight);
            }

            return new Size(w, h);
        }
        #endregion

    }
}
